package cn.btks.commonserver.util.poi;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangjing
 * 2020/3/20 16:29
 * 写入word样式设置
 */
public class XWPRunUtil {

    //标题
    public static void title(XWPFDocument xwpfDocument, String title) {
        XWPFParagraph paragraphX = xwpfDocument.createParagraph();
        XWPFRun runX = paragraphX.createRun();
        runX.setText(title);
        runX.setBold(true);//加粗
        runX.setFontFamily("黑体");//字体
        runX.setFontSize(18);//字体大小
//        runX.addBreak();
        paragraphX.setAlignment(ParagraphAlignment.CENTER);//居中对齐
    }

    //一级序号及标题
    public static void onelevelMenuNoAndSubject(XWPFDocument xwpfDocument, String no, String subject) {
        XWPFParagraph paragraphX = xwpfDocument.createParagraph();
        XWPFRun runX1 = paragraphX.createRun();
        runX1.setText(no + " " + subject);
        runX1.setBold(true);//加粗
        runX1.setFontFamily("黑体");//字体
        runX1.setFontSize(16);//字体大小
        runX1.setTextPosition(24); //设置两行之间的行间
        runX1.addBreak();
        paragraphX.setAlignment(ParagraphAlignment.LEFT);//左对齐
    }

    //二级序号及标题
    public static void twolevelMenuNoAndSubject(XWPFDocument xwpfDocument, String no, String subject) {
        XWPFParagraph paragraphX = xwpfDocument.createParagraph();
        XWPFRun runX2 = paragraphX.createRun();
        runX2.setText(no + " " + subject);
        runX2.setBold(true);//加粗
        runX2.setFontFamily("黑体");//字体
        runX2.setFontSize(14);//字体大小
        runX2.setTextPosition(24); //设置两行之间的行间
        runX2.addBreak();
        paragraphX.setAlignment(ParagraphAlignment.LEFT);//左对齐
    }

    //三级序号及标题
    public static void threelevelMenuNoAndSubject(XWPFDocument xwpfDocument, String no, String subject) {
        XWPFParagraph paragraphX = xwpfDocument.createParagraph();
        XWPFRun runX3 = paragraphX.createRun();
        runX3.setText(no + " " + subject);
        runX3.setBold(true);//加粗
        runX3.setFontFamily("黑体");//字体
        runX3.setFontSize(12);//字体大小
        runX3.setTextPosition(24); //设置两行之间的行间
        runX3.addBreak();
        paragraphX.setAlignment(ParagraphAlignment.LEFT);//左对齐
    }

    //片段
    public static void partContent(XWPFDocument xwpfDocument, String content) {
        XWPFParagraph paragraphX = xwpfDocument.createParagraph();
        XWPFRun runX4 = paragraphX.createRun();
        runX4.addTab(); //缩进
        runX4.setText(content);
        runX4.setBold(false);//加粗
        runX4.setFontFamily("宋体");//字体
        runX4.setFontSize(12);//字体大小
        runX4.setTextPosition(24); //设置两行之间的行间
        runX4.addBreak();
//        paragraphX.setAlignment(ParagraphAlignment.LEFT);//左对齐
//        runX4.addCarriageReturn();//回车键
    }

//    /**
//     * 项目人力资源配置表
//     *
//     * @param xwpfDocument xwpfDocument
//     * @param chaptersNo   章节号
//     * @param teamList     组成员
//     */
//    public static void tableTeamList(XWPFDocument xwpfDocument, String chaptersNo, String tableName, List<Team> teamList) {
//
//        List<XWPFParagraph> paragraphList = xwpfDocument.getParagraphs();
//        for (XWPFParagraph paragraph : paragraphList) {
//            String text1 = "";
//            String text = paragraph.getText();
//            if (text.indexOf(" ") != -1) {
//                text1 = text.substring(0, text.indexOf(" "));
//            }
//            if (text1.equals(chaptersNo)) {
//
//                XmlCursor cursor = paragraph.getCTP().newCursor();
//                //将光标移动到下一个段落，因为光标生成是在段落的最开始位置 所以需要向下移动一个Xml的光标，也就是将光标移动到下一个段落之前，
//                cursor.toNextSibling();
//
//                //添加标题
//                XWPFRun xwpfRun = paragraph.createRun();
//                xwpfRun.setTextPosition(14); //设置两行之间的行间
//                xwpfRun.setFontSize(10);//字体大小
//                xwpfRun.setText("表" + chaptersNo + "  " + tableName);
//                xwpfRun.setTextPosition(14); //设置两行之间的行间
//
//                // 在指定游标位置插入表格
//                XWPFTable table = xwpfDocument.insertNewTbl(cursor);
//                setTableLocation(table, "center");
//                XWPFTableRow row_1 = table.getRow(0);
//                row_1.getCell(0).setText("序号");
//                row_1.addNewTableCell().setText("姓名");
//                row_1.addNewTableCell().setText("角色");
//                row_1.addNewTableCell().setText("职称");
//                row_1.addNewTableCell().setText("内容");
//
//                int i = 1;
//                for (Team team : teamList) {
//                    XWPFTableRow row_x = table.createRow();
//                    row_x.getCell(0).setText(String.valueOf(i));
//                    row_x.getCell(1).setText(team.getUsername());
//                    row_x.getCell(2).setText(team.getProjectRole().getName());
//                    row_x.getCell(3).setText(team.getAcademicName());
//                    row_x.getCell(4).setText(team.getProjectRole().getConcreteWork());
//                    i++;
//                }
//                break;
//            }
//        }
//
//    }
//
//    /**
//     * 设置表格位置
//     *
//     * @param xwpfTable
//     * @param location  整个表格居中center,left居左，right居右，both两端对齐
//     */
//    public static void setTableLocation(XWPFTable xwpfTable, String location) {
//        CTTbl cttbl = xwpfTable.getCTTbl();
//        CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
//        CTJc cTJc = tblpr.addNewJc();
//        cTJc.setVal(STJc.Enum.forString(location));
//    }

    /**
     * 拷贝word
     * @param oldXWPFParagraph
     * @param newXWPFParagraph
     */
    public static void copyAllRunsToAnotherParagraph(XWPFParagraph oldXWPFParagraph, XWPFParagraph newXWPFParagraph) {
        final int DEFAULT_FONT_SIZE = 10;

        for (XWPFRun run : oldXWPFParagraph.getRuns()) {
            String textInRun = run.getText(0);
            if (textInRun == null || textInRun.isEmpty()) {
                continue;
            }

            int fontSize = run.getFontSize();
            //System.out.println("run text = '" + textInRun + "' , fontSize = " + fontSize);

            XWPFRun newRun = newXWPFParagraph.createRun();

            // Copy text
            newRun.setText(textInRun);

            // Apply the same style
            newRun.setFontSize((fontSize == -1) ? DEFAULT_FONT_SIZE : run.getFontSize());
            newRun.setFontFamily(run.getFontFamily());
            newRun.setBold(run.isBold());
            newRun.setItalic(run.isItalic());
            newRun.setColor(run.getColor());
        }
    }

    public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
        CTBody src1Body = src.getDocument().getBody();
        CTBody src2Body = append.getDocument().getBody();

        List<XWPFPictureData> allPictures = append.getAllPictures();
        // 记录图片合并前及合并后的ID
        Map<String, String> map = new HashMap();
        for (XWPFPictureData picture : allPictures) {
            String before = append.getRelationId(picture);
            //将原文档中的图片加入到目标文档中
            String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
            map.put(before, after);
        }
        appendBody(src1Body, src2Body, map);
    }

    private static void appendBody(CTBody src, CTBody append, Map<String, String> map) throws Exception {
        XmlOptions optionsOuter = new XmlOptions();
        optionsOuter.setSaveOuter();
        String appendString = append.xmlText(optionsOuter);
        String srcString = src.xmlText();
        String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
        String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
        String sufix = srcString.substring(srcString.lastIndexOf("<"));
        String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));

        if (map != null && !map.isEmpty()) {
            //对xml字符串中图片ID进行替换
            for (Map.Entry<String, String> set : map.entrySet()) {
                addPart = addPart.replace(set.getKey(), set.getValue());
            }
        }
        //将两个文档的xml内容进行拼接
        CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);

        src.set(makeBody);
    }
}
